[질문]
C++ 템플릿 도움좀 주십쇼
익명(121.141)
2022-01-29 12:29
추천 0
#include <iomanip>
#include <iostream>
#include <string>
#include <type_traits>
template<typename T
>
struct impl_ostream_operator
{
template<class U>
static auto test(U
*) -> decltype(std
::declval
<std
::ostream
>() << std
::declval
<U
>());
template<typename>
static auto test(...) -> std
::false_type
;
using type
= typename std
::is_same
<std
::ostream
&, decltype(test
<T
>(nullptr))>::type
;
static constexpr bool value
= type
::value
;
};
template<typename T
>
using impl_ostream_operator_t
= typename impl_ostream_operator
<T
>::type
;
template<typename T
>
constexpr bool impl_ostream_operator_v
= impl_ostream_operator
<T
>::value
;
int main()
{
std
::cout
<< std
::boolalpha
<< impl_ostream_operator_v
<double> // true
<< '\n'
<< impl_ostream_operator_v
<std
::string
> // false
<< '\n';
}
ostream 오퍼레이터를 구현했는지 검사하는 템플릿을 만들고 싶은데
double 같은 기본 숫자 타입들은 원하는데로 작동하지만
std::string은 그렇지가 않네요
어디서 잘못되었을까요?
MinGW에서는 둘 다 true나옴
근데 VS에서는 string은 false나오는데, basic_ostream&&이라고 타입이 나와서 basic_ostream&이랑 비교하면 is_same이 false 나오는 것같음
윗댓글대로의 문제가 있어서 구조체 하단에서 is_same 검사할때 std::ostream이랑 std::decay_t한거랑 비교하삼
위에서 다 답을 줬네 타입 비교할 때는 const, reference 등은 제거하고 원형을 비교해야 이런 이상한 조건을 피할 수 있음