如何为部分类型名称定义函数
How do I define function for part of typenames
我有一个类似的代码
#include <iostream>
struct X {
};
template <typename T>
struct A {
static int a();
};
template <>
int A<int>::a() {
return 42;
}
template <>
int A<X>::a() {
return 0;
}
int main() {
std::cout << A<int>().a() << std::endl;
std::cout << A<X>().a() << std::endl;
return 0;
}
现在我想为所有算术类型返回42,即std::is_arithmetic<T>::type
是std::true_type
我试过
template <typename T, typename U = std::true_type>
struct A {
static int a();
};
template <typename T>
int A<T, typename std::is_arithmetic<T>::type>::a() {
return 42;
}
但我得到了以下错误:
a.cpp:12:51: error: invalid use of incomplete type ‘struct A<T, typename std::is_arithmetic<_Tp>::type>’
int A<T, typename std::is_arithmetic<T>::type>::a() {
^
a.cpp:7:8: error: declaration of ‘struct A<T, typename std::is_arithmetic<_Tp>::type>’
struct A {
^
还尝试了
template <typename T>
struct A {
static int a();
};
template <typename T, typename E = typename std::enable_if<std::is_arithmetic<T>::value>::type>
int A<T>::a() {
return 42;
}
错误:
a.cpp:12:13: error: default argument for template parameter for class enclosing ‘static int A<T>::a()’
int A<T>::a() {
^
a.cpp:12:13: error: got 2 template parameters for ‘static int A<T>::a()’
a.cpp:12:13: error: but 1 required
实现这一目标的正确方法是什么?它真的存在吗?
我知道我可以做到这一点,一次专门化所有结构,但我不想这样,因为实际上还有几个函数,它们应该是常见的
不,那行不通。相反,尝试定义一个单独的类型,该类型将包含42或0,基于is_athmetic。您可以将boost::mpl::if_用于
template< typename T > struct Res
{
typedef typename if_<
std::is_arithmetic<T>
, static_value<42>
, static_value<0>
>::type value;
};
相关文章:
- 在命名空间中定义函数还是限定函数
- 为什么在定义函数之前先声明它
- 使用用户定义函数的字符串反转
- 用户定义函数中的指针和输入
- 这个c++代码是如何在没有定义函数的情况下运行的
- 具有外部"c"和程序集的未定义函数
- 已定义函数时出现 G++ "未定义的引用"错误
- 将自定义函数传递到基抽象类中以延迟执行
- C++使用 rand 定义函数语法
- Arduino:在 loop() 和自定义函数中运行相同的代码时出现问题
- 将具有固定签名的自定义函数名称注入 CRTP
- 使用定义函数模板别名
- 是否可以使用单个定义定义函数的常量和常规版本?(使用模板,自动,decltype等)
- 在内联程序集中定义函数和从 C++ 调用时出现问题
- 在 Metal 着色器代码中,如何定义函数的 in/out 参数变量?
- 声明和定义函数静态会产生"undefined reference to function_name()"
- 朋友定义函数的名称空间是什么
- 介子 对用户定义函数的未定义引用
- 如何使用 "using" 关键字定义函数原型/签名
- 在 C 结构中定义C++函数