C ++ 11 init模板化成员变量

时间:2014-05-22 22:09:33

标签: templates c++11

我想要有构造函数的模板化成员变量,如下所示:

struct S{
    //typedef S ThisT;

    template<class IdsT, class DataT>
    struct CallbackPack{
        /*constexpr */CallbackPack(IdsT &selfIds):
            selfIds(selfIds){}

        const IdsT  &selfIds;
    };    

    const  CallbackPack<S, S> callbackPack123 = CallbackPack<S, S>((*this));
};

但是当我尝试编译时,我得到了错误。

g++-4.8 -std=c++11 -O2 -Wall -pedantic -pthread main.cpp && ./a.out
main.cpp:16:65: error: expected ';' at end of member declaration
     const  CallbackPack<S, S> callbackPack123 = CallbackPack<S, S>((*this));
                                                                 ^
main.cpp:16:66: error: expected unqualified-id before '>' token
     const  CallbackPack<S, S> callbackPack123 = CallbackPack<S, S>((*this));
                                                                  ^
main.cpp:16:65: warning: non-static const member 'const S::CallbackPack<S, S> S::S' in class without a constructor [-Wuninitialized]
     const  CallbackPack<S, S> callbackPack123 = CallbackPack<S, S>((*this));
                                                                 ^
main.cpp:16:62: error: wrong number of template arguments (1, should be 2)
     const  CallbackPack<S, S> callbackPack123 = CallbackPack<S, S>((*this));
                                                              ^
main.cpp:9:12: error: provided for 'template<class IdsT, class DataT> struct S::CallbackPack'
     struct CallbackPack{
            ^

http://coliru.stacked-crooked.com/a/ea9ed4482306ce17

2 个答案:

答案 0 :(得分:1)

正如Mooing Duck所说,这是编译器错误https://gcc.gnu.org/bugzilla/show_bug.cgi?id=52595

为避免这种情况,您应该添加括号:

const  CallbackPack<S, S> callbackPack123 = (CallbackPack<S, S>(*this));

答案 1 :(得分:0)

编辑:

如果我理解您的想法,请试用以下代码:

#include <iostream>
#include <tuple>
#include <functional>

struct S{
    S() : callbackPack123(*this) {}

    template<class IdsT, class DataT>
    struct CallbackPack{
        // Initializing reference with nullptr is NOT A GOOD THING.
        // I'm just doing it to prove that no default constructors are called.
        CallbackPack() : selfIds_(nullptr) {
            std::cout << "EMPTY CONSTRUCTOR CALLED\n";
        }
        CallbackPack(IdsT &selfIds) : selfIds_(selfIds) {
            std::cout << "IdsT CONSTRUCTOR CALLED\n";
        }

        const IdsT  &selfIds_;
    };    

    const  CallbackPack<S, S> callbackPack123;
};

int main()
{
    S s;
    return 0;
}

打印

IdsT CONSTRUCTOR CALLED

,没有别的,表明该成员是使用IdsT构造函数创建的。我希望这能回答你的问题。