2
我想從作爲模板參數傳遞給另一個類的類中獲取靜態方法的地址。下面是一個相比下來例如:如何從作爲模板參數傳遞的類中獲取靜態模板方法的地址
#include <iostream>
#include <array>
using namespace std;
typedef size_t Data;
class MyFunction
{
private:
static const std::array<std::string, 3> values;
public:
template<size_t N>
static void Func(const Data& aData)
{
size_t index = (N > aData ? 2 : (N == aData ? 1 : 0));
cout << "Function::Func<"<< N << ">:\t" << N << values[index] << aData << endl;
}
typedef decltype(&Func<0>) type;
};
const std::array<std::string, 3> MyFunction::values {"<", "=", ">"};
template<class Function, size_t N>
class FunctionManager
{
private:
static const typename Function::type func_;
static constexpr typename Function::type Create()
{
return &Function::Func<N>; //ERROR: Causes "overloaded function with no contextual information".
}
public:
void operator()(const Data &aData) const
{
func_(aData);
}
};
template<class Function, size_t N>
const typename Function::type FunctionManager<Function, N>::func_ = FunctionManager<Function, N>::Create();
int main()
{
static const size_t N = 6;
auto man = FunctionManager<MyFunction, N>();
man(N/2);
return 0;
}
您還可以找到的代碼here。問題是在Create()函數中,我得到「沒有上下文類型信息的重載函數的地址」錯誤。但是,如果我將&函數:: Func更改爲& MyFunction :: Func,它工作正常。我想使實際功能成爲模板參數,而不是硬編碼,任何人都有任何想法如何解決這個問題?請注意,我意識到有更簡單的方法來做我想做的事情,但實際的代碼而不是一個Function :: type使用索引技巧創建它們的數組等。任何幫助將不勝感激。
'&Function :: template Func' - 編譯器不知道你有一個模板,默認情況下需要一個值。 –
Xeo
可能的重複[哪裏和爲什麼我必須把「模板」和「typename」關鍵字?](http://stackoverflow.com/questions/610245/where-and-why-do-i-have-to -put-the-template-and-typename-keywords) – Xeo
聞起來有點像XY問題,你能否更詳細地說明你的Create()函數的用途,以及爲什麼你不想'硬編碼'具體函數的參考?你打算如何使用這個接口的客戶?任意選擇從他們的靜態方法來傳遞一個? –