如何将C++模板方法的返回类型声明为其他类中的静态方法
How to declare return type of C++ template method to be that of static method in other class?
我想做有效的C++11等效于以下(明显(无效的代码:
class StaticMethodClass {
public:
static int staticMethod(int a) {return 0;}
};
#include <type_traits>
template<class T> class ClassTemplate {
public:
decltype(T::staticMethod(int)) methodTemplate(int a);
};
template<class T>
decltype(T::staticMethod(int)) ClassTemplate<T>::methodTemplate(int a) {
return T::staticMethod(a);
}
template class ClassTemplate<StaticMethodClass>;
我从编译器中得到以下错误:
/tmp$ g++ -std=c++11 -c a.cpp
a.cpp:14:26: error: expected primary-expression before ‘int’
decltype(T::staticMethod(int)) ClassTemplate<T>::methodTemplate(int a) {
^
a.cpp:14:32: error: prototype for ‘decltype (T:: staticMethod(<expression error>)) ClassTemplate<T>::methodTemplate(int)’ does not match any in class ‘ClassTemplate<T>’
decltype(T::staticMethod(int)) ClassTemplate<T>::methodTemplate(int a) {
^
a.cpp:10:36: error: candidate is: int ClassTemplate<T>::methodTemplate(int)
decltype(T::staticMethod(int)) methodTemplate(int a);
^
/tmp$ g++ -dumpversion
4.8.3
我想做的事情可能吗?如果是,如何?
我不认为std::result_of
是这样工作的。它被定义为result_of<F(ArgTypes...)>
(请参阅cpprreference(。F
参数应该是类型。当您编写T::staticMethod
时,您给result_of
的是函数,而不是类型。
F必须是可调用类型、对函数的引用或对可调用类型的引用。正在使用ArgTypes调用F。。。必须是格式良好的表达式。
所以你们想要的是给result_of
这个函数的引用类型。指向该函数的指针由&T::staticMethod
给出,其类型由decltype(&T::staticMethod)
给出。此代码有效。
typename std::result_of<decltype(&T::staticMethod)(int)>::type methodTemplate(int i) {
return T::staticMethod(i);
}
另请注意Chris指出的typename
。
auto
应该会成功:
auto methodTemplate(int i) -> decltype(T::staticMethod(i)) {
return T::staticMethod(i);
}
在C++14中,您可以跳过decltype
:
auto methodTemplate(int i) {
return T::staticMethod(i);
}
这很有效(http://ideone.com/6pczX3):
decltype(T::staticMethod(int)) methodTemplate(int i) {
return T::staticMethod(i);
}
起初,我认为您可能只需要适当地添加typename
,但这并没有奏效。
decltype(T::staticMethod(int)) methodTemplate(int a);
应该是
decltype(T::staticMethod(0)) methodTemplate(int a);
或
decltype(T::staticMethod(std::declval<int>())) methodTemplate(int a);
(定义相同(。
演示
相关文章:
- GlobalAlloc而不是其他分配方法
- 尝试了解在导入的静态方法上使用删除方法时的错误
- 如何通过命名空间调用非静态方法
- 如何在没有实例的情况下获取非静态方法的类型?
- 调用从模板派生的类的静态方法,而不指定模板
- 如何在 c++ 中异步调用静态方法?
- C++ 将静态方法转换为简单方法
- 从另一个标头中的标头调用静态方法
- C++中静态方法的局部变量范围
- 使用 CMake 与其他静态库链接的静态库 - 一个有效,一个无效。为什么?
- 如何启用使用另一个类的静态方法的模板函数的自动推导,从而消除冗长的调用方代码
- 使用本机 JNI 静态方法实现C++ Java 运行时错误
- 当只有静态方法受到影响时,如何解决C++中的链接器错误?
- 静态变量在同一个翻译单元中被静态方法使用时是否保证被初始化?
- 为什么链接器报告全局函数的乘法定义符号,而不是类静态方法
- 从部分专用模板方法调用模板非静态方法
- 如何使用 c++ 在 cocos2dx 中定义非静态方法
- 访问其他类中的静态方法和静态布尔值
- 如何将C++模板方法的返回类型声明为其他类中的静态方法
- 静态方法中的对象创建是改变其他静态对象的私有成员变量