我基本上想在編譯時選擇一個分支,但不知道如何解決出現的錯誤。
這是代碼(鏈接):
#include <iostream>
#include <vector>
#include <type_traits>
template <typename charT>
struct Foo
{
using value_type = charT;
std::vector<value_type> vec;
void printVec( std::basic_ostream<charT>& out_stream )
{
out_stream.write( std::data( vec ), std::size( vec ) ).write( "\n", 1 );
}
};
// specialization for char
template <>
void Foo<char>::printVec( std::basic_ostream<char>& out_stream )
{
out_stream.write( std::data( vec ), std::size( vec ) ).write( "\n", 1 );
}
// specialization for wchar_t
template <>
void Foo<wchar_t>::printVec( std::basic_ostream<wchar_t>& out_stream )
{
out_stream.write( std::data( vec ), std::size( vec ) ).write( L"\n", 1 );
}
int main( )
{
using FooChar = Foo<char>;
using FooWideChar = Foo<wchar_t>;
#define IS_CHAR 1
#if IS_CHAR == 1
FooChar foo;
foo.vec.resize( 10, '$' );
#else
FooWideChar foo;
foo.vec.resize( 10, L'#' );
#endif
if constexpr ( std::is_same_v< decltype( foo )::value_type,
decltype( std::cout )::char_type > )
{
foo.printVec( std::cout );
}
else if constexpr ( std::is_same_v< decltype( foo )::value_type,
decltype( std::wcout )::char_type > )
{
foo.printVec( std::wcout ); // this is where the compile error occurs
}
else
{
static_assert( std::is_same_v< decltype( foo )::value_type,
decltype( std::cout )::char_type > ||
std::is_same_v< decltype( foo )::value_type,
decltype( std::wcout )::char_type >,
"character type not supported" );
}
}
錯誤資訊:
cannot convert 'std::wostream' {aka 'std::basic_ostream<wchar_t>'} to 'std::basic_ostream<char>&'
該訊息是不言自明的,但我仍然不知道如何解決這個問題。else if我猜如果編譯器不檢查分支內陳述句的語法,這個問題就不會出現。有什么辦法可以編譯上面的代碼片段嗎?
uj5u.com熱心網友回復:
將您的邏輯提升if constexpr到模板函式中:
template <typename charT>
void printIt( Foo<charT>& foo )
{
if constexpr ( std::is_same_v<charT, char> )
foo.printVec( std::cout );
else if constexpr ( std::is_same_v<charT, wchar_t> )
foo.printVec( std::wcout );
else
static_assert( sizeof(charT) == 0, "character type not supported" );
}
另外,請注意您不需要printVec()for 的兩個定義char。您可以簡單地在類中宣告它而無需定義:
void printVec( std::basic_ostream<charT>& out_stream );
應該是吧const,然后printIt()可以拿const Foo&。
轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/508190.html
標籤:C 模板 ostream if-constexpr
