2017-04-13 85 views
-1

我该如何做这样的事情?我想创建一个类C的对象并使用参数。详细说明,这里的错误是编译器将其读为转换,而不是使用参数创建对象。类C++中构造的模板类型对象

编辑:对于那些还不明白,foobar是无关紧要的。我已经删除它,因为错误仍然发生在没有该功能的情况下。

// define foobar else where 
template <class C> 
class Dummy { 
    void foo(int bar) { 
     C dumdum = C(bar); // Error - '<function-style-cast>': cannot convert from initializer-list to 'C' 
    } 
} 
+0

你看过[variadic模板和参数包](http://en.cppreference.com/w/cpp/language/parameter_pack)吗? –

+0

这对我有帮助吗? –

+0

这似乎不是有效的C++,foobar没有在任何地方声明。 – Vality

回答

0

这对我有帮助吗?

您可以使foofoo函数模板接受参数包以使其通用。

示例程序:

#include <iostream> 
#include <sstream> 
#include <string> 

template <class C> 
class Dummy { 
    public: 
     template <typename... Args> 
     void foo(Args... args) { 
      foobar(C(args...)); 
     } 
}; 

struct Foo 
{ 
    Foo(int, int) {} 
}; 

struct Bar 
{ 
    Bar(int) {} 
}; 

struct Baz 
{ 
}; 

void foobar(Foo) 
{ 
    std::cout << "In foobar(Foo)\n"; 
} 

void foobar(Bar) 
{ 
    std::cout << "In foobar(Bar)\n"; 
} 

void foobar(Baz) 
{ 
    std::cout << "In foobar(Baz)\n"; 
} 

int main() 
{ 
    Dummy<Foo>().foo(10, 20); 
    Dummy<Bar>().foo(10); 
    Dummy<Baz>().foo(); 
} 

输出:

In foobar(Foo) 
In foobar(Bar) 
In foobar(Baz) 
+0

这不回答问题。 – aschepler

+0

@aschepler,OP表示*我想创建一个C类对象并使用参数。*我错过了什么? –

0

你有没有尝试过这样的:

C dumdum(bar); 

或者:

C dumdum{bar}; 

0
class C { 
public: 
    C(int a) {} 
}; 

template <class C> 
class Dummy { 
public: 
    void foo(int bar) { 
     C dumdum = C(bar); 
    } 
}; 

int main() { 
    Dummy<C> dummy; 
    dummy.foo(2); 
    return 0; 
} 

我没有看到任何错误。