c++ - 如何将C++模板方法的返回类型声明为其他类中静态方法的返回类型?

标签 c++ c++11

我想执行与以下(显然)无效代码等效的有效 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...)> (参见 cppreference)。那F参数应该是一个类型。当你写 T::staticMethod你给result_of 函数,而不是类型

F must be a callable type, reference to function, or reference to callable type. Invoking F with ArgTypes... must be a well-formed expression.

所以你想要的是给result_of对该函数的引用类型。 &T::staticMethod 给出了指向该函数的指针。 , 其类型为 decltype(&T::staticMethod) .此代码有效。

typename std::result_of<decltype(&T::staticMethod)(int)>::type methodTemplate(int i) {
    return T::staticMethod(i);
}

另请注意 typename正如 Chris 指出的那样.

关于c++ - 如何将C++模板方法的返回类型声明为其他类中静态方法的返回类型?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40031233/

相关文章:

c++ - 将私有(private)部分保留在 c++ header 之外 : pure virtual base class vs pimpl

c++ - std::set 在使用 std::set.erase 后包含重复元素

c++ - 何时对多参数构造函数使用显式说明符?

c++ - 从一个不再存在的函数创建的 lambda 的内部框架修改 via 闭包中的变量是否安全

c++ - 如何在 QML 中访问 C++ 对象的列表属性

C++:数组的函数模板特化

C++使用相同的代码循环遍历对象和指针

C++11 如何使用 lambda 和高阶函数将 vector 转换为不同类型的 vector

c++ - 从此指针复制后尝试访问基类的成员时出现段错误

c++ - 从 Windows 迁移到 Ubuntu