小编Tho*_* B.的帖子

在模板本身中检索最里面的模板类型

是否可以模板中检索最内层类型的相同类型的堆叠模板?我想double在以下示例中检索该类型:

template<typename T>
struct is_a : std::false_type {};

template<typename T>
struct A
{
    using type = std::conditional_t<
        is_a<T>::value,
        T::type, // if it's an A, go deeper
        T>;      // if not, we're done
};
template<typename T>
struct is_a<A<T>> : std::true_type {};

int main()
{
    A<A<A<A<A<double>>>>>::type d = 3.0;
    return 0;
}
Run Code Online (Sandbox Code Playgroud)

这是出于这个问题的动机.此外,我发现这篇文章,表明它可能有一些事情typenametemplate关键字放置,但我无法让它自己工作.

c++ templates types

26
推荐指数
2
解决办法
1000
查看次数

无法将'const pointer const'传递给const ref

假设你有一组指针(是的......):

std::set<SomeType*> myTypeContainer;
Run Code Online (Sandbox Code Playgroud)

然后假设您要从SomeType的const方法搜索此集合:

bool SomeType::IsContainered() const
{
    return myTypeContainer.find(this) != myTypeContainer.end();
}
Run Code Online (Sandbox Code Playgroud)

这不起作用.方法中的thisptr是一个const SomeType *const,我不能把它放进去find.问题是find需要一个const-ref,在这种情况下,这意味着传递的指针被视为const,但不是它指向的东西.

有没有办法顺利解决这个问题(不改变设置的模板类型)?

c++ templates pointers const pass-by-const-reference

12
推荐指数
2
解决办法
1081
查看次数

我的type_trait在模板/非模板代码中的不同行为

在以下代码段中,has_bar行为主体和DoStuff方法的行为有所不同:

在主要方法中,a_bar == falseb_bar == true

执行此命令时,输出为2x“ Foo”。为什么?

#include <iostream>

struct A
{
    void Foo() { std::cout << "Foo" << std::endl; }
};

struct B : public A
{
    void Bar() {  std::cout << "Bar" << std::endl; }
};

template<typename, typename = void>
struct has_bar : std::false_type
{ };

template<typename T>
struct has_bar<T, std::void_t<decltype(T::Bar)>> : std::true_type
{ };

template<typename T>
void DoStuff(T t)
{
    if constexpr (has_bar<T>::value)
    {
        t.Bar();
    }
    else
    { …
Run Code Online (Sandbox Code Playgroud)

c++ type-traits c++17

4
推荐指数
1
解决办法
122
查看次数