7

C++:模板函数限定参数类型

 3 years ago
source link: https://www.lpime.cn/article/119
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
neoserver,ios ssh client
C++:模板函数限定参数类型 - Ryan_naiquan

C++

/************************************************************************/
/* c++模板函数如何限定参数类型
* https://www.zhihu.com/question/403570202/answer/1310165034
/************************************************************************/

#include <iostream>
#include <type_traits>
#include <string>

template<typename T>
concept IsNumber = std::is_arithmetic<T>::value;

template<IsNumber T>
void test(T t)
{
	std::cout << t << std::endl;
}

namespace detail
{
	template<class T>
	constexpr bool valid() {
		if constexpr (
			std::is_same_v<T, int> ||
			std::is_same_v<T, double> ||
			std::is_same_v<T, char> ||
			std::is_same_v<T, float>
			) {
			return true;
		}
		else {
			return false;
		}
	}
}


template<class T, std::enable_if_t<detail::valid<T>(), int> = 0>
void testA(T t)
{
	std::cout << t << std::endl;
}

template<typename Type> inline
typename std::enable_if_t<std::is_arithmetic_v<Type>, int> testB(Type&& type) 
{
	return true;
}

template<typename Type> inline
void processImpl(Type&& type) {
	if constexpr (std::is_arithmetic_v<Type>)
	{
		std::cout << "true" << std::endl;
	}
	else 
	{
		std::cout << "false" << std::endl;
	}
}

int main()
{
	int a = 1;
	std::string str = "aaa";  //传入test error;
	testA(a);
	testB(std::move(a));
	processImpl(std::move(a));
	test(a);
	return 0;
}

本文由 Ryan 创作,采用 知识共享署名4.0 国际许可协议进行许可
本站文章除注明转载/出处外,均为本站原创或翻译,转载前请务必署名
最后编辑时间为: 2021/05/20 16:02


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK