是否可以从模板中检索最内层类型的相同类型的堆叠模板?我想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)
这是出于这个问题的动机.此外,我发现这篇文章,表明它可能有一些事情typename
或template
关键字放置,但我无法让它自己工作.
假设你有一组指针(是的......):
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)
这不起作用.方法中的this
ptr是一个const SomeType *const
,我不能把它放进去find
.问题是find
需要一个const-ref,在这种情况下,这意味着传递的指针被视为const,但不是它指向的东西.
有没有办法顺利解决这个问题(不改变设置的模板类型)?
在以下代码段中,has_bar
行为主体和DoStuff
方法的行为有所不同:
在主要方法中,a_bar == false
和b_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)