简体   繁体   English

无法推断功能参数的非类型模板参数

[英]Cannot deduce non-type template parameter of a function parameter

This might be something really simple, but I cannot figure out why this code does not compile 这可能确实很简单,但是我无法弄清楚为什么此代码无法编译

#include <type_traits>

template <std::size_t Size, std::size_t Align>
void foo(std::aligned_storage_t<Size, Align>&) {}

int main() {
    auto storage = std::aligned_storage_t<100, 8>{};
    foo(storage);
}

( https://wandbox.org/permlink/PdBwAWVh6N9rkTE2 ) https://wandbox.org/permlink/PdBwAWVh6N9rkTE2

How can I get this to work? 我该如何工作? And why does not this compile? 为什么不编译呢?


The usecase is that foo() is a suite of overloads on unrelated types like aligned_storage_t , int , double , etc. And the aligned_storage_t instance represents memory that foo() knows how to reinterpret and use. 用例是foo()是不相关类型(如aligned_storage_tintdoublefoo()的重载套件。而aligned_storage_t实例表示foo()知道如何重新解释和使用的内存。

It doesn't work because std::aligned_storage_t is not a class, it's a type alias for some implementation defined type. 它不起作用,因为std::aligned_storage_t不是类,它是某些实现定义的类型的类型别名。 In fact what you have is: 实际上,您拥有的是:

template <std::size_t Size, std::size_t Align>
void foo(typename std::aligned_storage<Size, Align>::type);

Size and Align cannot be deduced from this as it is a non-deduced context. SizeAlign方式无法从中推导出,因为它是非推论上下文。 You need to replace both instances of std::aligned_storage_t with std::aligned_storage . 您需要用std::aligned_storage替换两个std::aligned_storage_t实例。 Then if you need the aligned type you would access that with ::type . 然后,如果您需要对齐的类型,则可以使用::type访问。

Size and Align is not deducible with std::aligned_storage<Size, Align>::type . 使用std::aligned_storage<Size, Align>::type无法std::aligned_storage<Size, Align>::type Size and Align

You might use sizeof / alignof to retrieve (nearly) initial value: 您可以使用sizeof / alignof检索(几乎)初始值:

template <typename T>
void foo(const T&)
{
    constexpr std::size_t size = sizeof(T);
    constexpr std::size_t alignment = alignof(T);

    std::cout << size << " "<< alignment << std::endl;
}

Demo (got size of 104 instead of input 100 due to alignment for your example) 演示 (由于示例对齐,获取的大小为104而不是输入100)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM