c++ - VS2013模板类奇怪的行为

标签 c++ templates c++11 constructor visual-studio-2013

我有一个模板类:

template <class T>
class Wrapper {
public:
    Wrapper() {};

    Wrapper(const T& object) : mObject(object){ };

    template <class F, class... Args >
    typename void operation(const F& f, Args... args)
    {
        std::cout << "intercept";
        (mobject.*f)(args...);
    }

private:
    T mObject;
};

然后我这样使用它:

struct thing{
    void doSomething(char c) { cout << "dosomething on " << c; };
};

Wrapper<thing> p;
p.operation(&thing::doSomething, 'g');

这很好,并输出“Intercept then dosomething on g”。然后,如果我尝试像这样使用 Wrapper 的其他构造函数:

Wrapper<thing> p2(thing());
p2.operation(&thing::doSomething, 'f');

VS2013 在我尝试调用 p2 上的某些内容的行上出现编译失败。它表示操作的左侧不是类/结构/union 。

嗯?我是否遗漏了一些明显的东西?

最佳答案

这声明了一个函数p2 :

Wrapper<thing> p2(thing());

返回 Wrapper<thing>并且有一个类型为 thing(*)() 的未命名参数。您需要:

Wrapper<thing> p2((thing()));

thing t;
Wrapper<thing> p2(t);

关于c++ - VS2013模板类奇怪的行为,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19801263/

相关文章:

c++ - 使用 constexpr 方法在结构内部进行模板参数化

c++ - 如何将对象 move 到未初始化的内存中?

c++ - 为什么 C++11 中的 `i = i++ + 1` 行为未定义?

C++继承循环依赖

c++ - 如何将函数回调传递给类成员?

c++ - 将 boost::make_recursive_variant 与元组一起使用

c++ - 使用 C++11 拆分字符串

c++ - 抑制 -Wtautological-compare 警告

c++ - 声明指向 char 数组的指针数组

c++ - (Obj) C++ : Instantiate (reference to) class from template, 访问其成员?