我想只为数字写有条件的模板。
//in header file
template <typename T,
typename = typename std::enable_if<std::is_arithmetic<T>::value, T>::type
>
class Foo
{
public:
Foo();
};
#include "Foo.inline"和
//In inline file
template <
typename T
>
Foo<T>::Foo()
{
};但是,这并不是编译。如何在单独的文件中使用模板实现的语法?
发布于 2015-09-27 10:31:28
std::enable_if对于触发替换失败非常有用,这样编译器就可以退回到另一个重载/专门化。
如果要验证模板参数,请在static_assert中添加适当的条件。
template <typename T>
class Foo
{
static_assert(std::is_arithmetic<T>::value,
"T must be an arithmetic type");
public:
Foo();
};
template <typename T>
Foo<T>::Foo()
{
}或约束c++20
template <typename T>
requires std::is_arithmetic_v<T>
class Foo
{
// ...
};发布于 2015-09-27 10:20:32
定义中应使用第二个模板参数。
//in header file
template <typename T,
typename Enable = typename std::enable_if<std::is_arithmetic<T>::value, T>::type
>
class Foo
{
public:
Foo();
};
//In inline file
template <typename T, typename Enable>
Foo<T, Enable>::Foo()
{
};https://stackoverflow.com/questions/32806840
复制相似问题