【问题标题】:Member function template using boost::function使用 boost::function 的成员函数模板
【发布时间】:2014-01-30 07:17:26
【问题描述】:

以下TestClass 有效:

#include <iostream>
#include <boost/function.hpp>
#include <boost/bind.hpp>

void ext_fun(const float f, int i)
{
    std::cout << f << '\t' << i << std::endl;
}

template <typename T>
class TestClass
{
public:
    boost::function <void (const T)> test_fun;
};

int main()
{
    TestClass<float> tt;
    tt.test_fun = std::bind(ext_fun, std::placeholders::_1, 10);
    tt.test_fun(2.1);
    return(0);
}

但是,我更愿意将test_fun 定义为成员函数模板,即类似

class TestClass
{
public:
    template <typename T> boost::function <void (const T)> test_fun;
};

但是如果我这样做,我会得到这个编译器错误:“错误:数据成员‘test_fun’不能是成员模板”

是否可以使用boost::function 定义成员函数模板?如果是,怎么做?

谢谢

--马特奥

【问题讨论】:

  • 抱歉,这没有意义——这不是“函数模板”的意思。你问的是“我能把struct Foo { int a; };变成struct Foo { template &lt;typename T&gt; T a; };吗”,你不能。
  • @Kerrek SB 我指的是第一个例子here,或问题here,但使用boost::function

标签: c++ templates boost boost-function


【解决方案1】:

是否可以使用boost::function 定义成员函数模板?如果是,怎么做?

我认为您在这里有些困惑。函数模板首先是一个函数。您的test_fun 不是函数,它是TestClass 类的成员对象。成员对象不能在 C++ 中模板化。

【讨论】:

  • 好的,重点是:类方法可以模板化(如here),但如果我使用boost::function,我实际上并没有方法,而是一个成员对象 代替。所以不能模板化。这是正确的吗?
  • @MatteoM.,“类方法”术语在 C++ 中不存在:您应该习惯于“成员函数”。但是,是的,这个概念是正确的。 boost::function 是一个类类型,它导致声明 boost::function &lt;void (const T)&gt; test_fun; 是一个对象,不能模板化。
猜你喜欢
  • 2010-12-27
  • 1970-01-01
  • 1970-01-01
  • 2011-01-01
  • 2013-07-13
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-09-27
相关资源
最近更新 更多