C++ 模板运算符()重载C++;

C++ 模板运算符()重载C++;,c++,templates,syntax,operators,operator-overloading,C++,Templates,Syntax,Operators,Operator Overloading,有人已经问了这个问题,但是线程最终没有回答原来的问题 假设你有: template<size_t i, class f_type> void call_with_i(f_type f); 模板 无效调用_与_i(f_类型f); 函子类型为: a) 具有具有以下签名的方法的结构: template<size_t i> operator()() const; 模板操作符()()常量; 或者,b)一个如下所示的函数: template<size_t i>

有人已经问了这个问题,但是线程最终没有回答原来的问题

假设你有:

template<size_t i, class f_type>
void call_with_i(f_type f);
模板
无效调用_与_i(f_类型f);
函子类型为:

a) 具有具有以下签名的方法的结构:

template<size_t i> operator()() const;
模板操作符()()常量;
或者,b)一个如下所示的函数:

template<size_t i> foo();
template foo();

我希望“call_with_I(foo)”等同于“foo()”,但我无法找到实现这一点的正确语法。我会对一个只做(a)但(a)+(b)的解决方案感到满意。我已经尝试过这些语法:

f< i >(); // doesn't work
f()< i >; // doesn't work
f.operator< i >(); // doesn't work
f.operator()< i >; // doesn't work
f.operator()< i >(); // works on msvc, but doesn't work on gcc. 
f();//不起作用
f();//不起作用
f、 运算符();//不起作用
f、 运算符();//不起作用
f、 运算符()();//适用于msvc,但不适用于gcc。
如何使用显式模板参数调用运算符()?有没有一种方法可以以同样的语法调用模板自由函数的方式调用它?

p、 如果你想知道我用这个做什么,那是因为我在写一个函数repeat,repeat调用f(0),然后f(1)。。。f(10)。我使用它通过索引并行遍历多个boost::fusion向量。是的,我可以使用迭代器,也可以只使用命名成员函数,但我仍然想知道答案


编辑说明:我删除了这些内容,因为将模板自由函数作为参数传递没有任何意义。

成员模板是一个依赖名称,因为其语义取决于
f\u type的类型。这意味着您应该将“模板”放在其名称之前(以消除“小于”标记的使用歧义),类似于将
typename
放在从属限定名称之前的方式:

template<size_t i, class f_type>
void call_with_i(f_type f) {
  f.template operator()<i>();
  // f.template foo<i>();
}
这对于模板化构造函数来说非常方便,对于模板化构造函数,您无法执行
f_type()()
或其他操作。在那种情况下,它们必须是可推断的

#包括
#include <iostream>

template<size_t i, class f_type> void call_with_i(f_type f);

struct A {

    template < size_t i >
    void operator()() const {
        /* no link err in demo */
    }

    template < size_t i >
    void foo() {
        /* no link err in demo */
    }
};

int main(int argc, char * const argv[]) {
    A f;

    enum { Constant = 42 };

    f.operator()<Constant>();
    f.foo<Constant>();

    return 0;
}
模板无效调用_与_i(f_类型f); 结构A{ 模板 void运算符()()常量{ /*演示中没有链接错误*/ } 模板 void foo(){ /*演示中没有链接错误*/ } }; int main(int argc,char*const argv[]{ A f; 枚举{常数=42}; f、 运算符(); f、 foo(); 返回0; }
有没有一种方法可以用同样的语法调用模板化的自由函数来调用它


你能澄清一下吗?(伪代码之类的)

在像您这样的情况下,我会使用boost::function作为函子类型。然后,您可以同时传递函数对象和函数指针,同时保留相同的接口。

没有回答,因为您不能。@Johannes:为什么不使用SFINAE专门处理函数?效果很好!太棒了。你是我的元英雄。啊,你关于使用mpl::int_u的想法也很聪明。@laulabs.mp,很高兴能提供帮助:)我发现像@laulabs.mp这样试图传递函数模板是没有意义的。因此,在这种情况下,使用
size\u t\u
的解决方法是值得怀疑的。修改了相应的答案。实际上,我关于模板自由函数的一点只是胡说八道,因为你不能将函数模板作为参数传递。
template<size_t i> void operator()(size_t_<i>) const {
  // i was deduced automatically by the function argument. 
}
#include <iostream>

template<size_t i, class f_type> void call_with_i(f_type f);

struct A {

    template < size_t i >
    void operator()() const {
        /* no link err in demo */
    }

    template < size_t i >
    void foo() {
        /* no link err in demo */
    }
};

int main(int argc, char * const argv[]) {
    A f;

    enum { Constant = 42 };

    f.operator()<Constant>();
    f.foo<Constant>();

    return 0;
}