Suppose I have this class:
class foo
{
public:
foo() { }
foo(const std::string& s) : _s(s) { }
private:
std::string _s;
};
Which is a member of another class:
class bar
{
public:
bar(bool condition) :
_f(condition ? 开发者_开发技巧"go to string constructor" : **go to empty ctor**)
{
}
private:
foo _f;
};
When initializing _f in bar's member initialization list I would like to choose which constructor of foo to invoke based on condition.
What can I put instead of go to empty ctor to make this work? I thought of putting foo(), is there another way?
The result of a conditional operator is always a fixed type determined at compile time by finding a common type that both options can be converted to. (The exact rules are a little involved, but in common use it usually 'does the right thing'.)
In your example the simplest thing to do is to let that type be a temporary foo and then use the copy constructor to intialize _f in bar.
You can do this as follows.
_f( condition ? foo("string") : foo() )
If passing an empty string is the equivalent of calling to no-arg constructor you could do the following:
_f(condition ? "string" : "")
This would save you the copy.
加载中,请稍侯......
精彩评论