相关疑难解决方法(0)

为什么未使用的成员模板功能的类模板实例化失败

这有什么问题:

#include <type_traits>

struct A;

template<typename T>
struct B
{
    template<typename=std::enable_if<std::is_copy_constructible<T>::value>>
    void f1() {}
};

template<typename T>
struct C {};


// Type your code here, or load an example.
int main() {
    // Following fails
    B<A> b;
    // Could use this:
    // b.f1<C>();

    // This complies
    C<A> c;

    return 0;
}

/* This to be in or not doesn't make a difference
struct A
{};
*/
Run Code Online (Sandbox Code Playgroud)

我在这里尝试过:https : //godbolt.org/z/NkL44s,使用了不同的编译器:

  • x86-64 gcc 9.2:编译
  • x86-64 gcc(trunk):失败
  • x86-64 clang 6.0.0:编译
  • x86-64 …

c++ templates

5
推荐指数
1
解决办法
98
查看次数

形成对void的引用

我有一个模板类,应该允许void作为模板参数.这个类有一个传递参数引用的函数,所以我做了以下事情:

template <typename T>
struct trait
{
    typedef typename boost::conditional<
        boost::is_void<T>::value,
        void, T &
    >::type type;
};

template <typename T>
struct foo
{
    typename trait<T>::type ref()
    {
        // do something
    }
};
Run Code Online (Sandbox Code Playgroud)

然而编译器声称我会void在实例化中形成一个引用struct trait<void>.为什么这样,我怎样才能实现我的目标?

c++ templates

3
推荐指数
1
解决办法
3236
查看次数

标签 统计

c++ ×2

templates ×2